package com.fingard.dsp.bank.directbank.czb02;

import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IRealTime;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * 浙商银行代收协议签约
 * <p>
 * 参考文档：浙商银行收付通接口规范（代收）.doc
 *
 * @author FanH
 * @date 2019/9/19
 */
public class CZB02RealTime extends CZB02Base implements IRealTime {
    /**
     * 开发接口：
     * 1. 3.3.3.5	第三方代理支付[0005]
     */
    @Override
    public RetAtsSingle d_9108_RealTimeRec(ReqSingle p_req9108) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req9108.singleDetail.recAct, "");
            if (actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath) || !FileHelper.existFile(actItem.ownCertFilePath)) {
                tmpRetDetail.respCode = "0";
                if (actItem == null) {
                    tmpRetDetail.respInfo = "未找到账号[" + p_req9108.singleDetail.recAct + "]批量商户配置信息";
                } else {
                    tmpRetDetail.respInfo = "账号[" + p_req9108.singleDetail.recAct + "]证书文件不存在";
                }

                tmpRetDetail.transAmt = p_req9108.singleDetail.payAmount;
                tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
                tmpRetDetail.transState = PaymentState.FAIL_Payment;
                tmpRetDetail.payInfoCode = FailCode.E9981;

                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            } else {
                CZB02Header bankHeader = new CZB02Header();
                bankHeader.transCode = "0005";
                bankHeader.reqSeqNo = p_req9108.singleDetail.askNumber;

                XmlTextWriter xmlWriter = new XmlTextWriter();
                StringBuilder reqMsg = new StringBuilder();

                writeCommonHeader(xmlWriter, actItem, bankHeader);
                xmlWriter.writeStartElement("body");
                xmlWriter.writeElementString("xyh" , p_req9108.singleDetail.payAct);//协议号
                reqMsg.append("<xyh>" + p_req9108.singleDetail.payAct + "</xyh>");//协议号

                //指定收款账号(0不指定，1指定)
                String isDesignatedAccount = getBankConfig().getValueAsString("isDesignatedAccount");
                if ("1".equals(isDesignatedAccount)) {
                    xmlWriter.writeElementString("zdskzh" , "1");//指定收款账号
                    reqMsg.append("<zdskzh>1</zdskzh>");//指定收款账号

                    xmlWriter.writeElementString("skzh" , p_req9108.singleDetail.payAct);//收款账号
                    reqMsg.append("<skzh>" + p_req9108.singleDetail.payAct + "</skzh>");//收款账号
                } else {
                    xmlWriter.writeElementString("zdskzh" , "0");//指定收款账号
                    reqMsg.append("<zdskzh>0</zdskzh>");//指定收款账号

                    xmlWriter.writeElementString("skzh" , "");//收款账号
                    reqMsg.append("<skzh></skzh>");//收款账号
                }
                xmlWriter.writeElementString("je" , p_req9108.singleDetail.payAmount);//金额
                reqMsg.append("<je>" + p_req9108.singleDetail.payAmount + "</je>");//金额

                xmlWriter.writeElementString("yt" , p_req9108.singleDetail.useType);//用途
                reqMsg.append("<yt>" + p_req9108.singleDetail.useType + "</yt>");//用途

                String smsCode = p_req9108.singleDetail.smsCode;
                if (!"".equals(smsCode) && smsCode != null) {
                    xmlWriter.writeElementString("dxyzm", smsCode);//短信验证码
                    reqMsg.append("<dxyzm>" + smsCode + "</dxyzm>");//短信验证码

                    xmlWriter.writeElementString("yzmxh", smsCode);//验证码序号
                    reqMsg.append("<yzmxh>" + smsCode + "</yzmxh>");//验证码序号
                }

                xmlWriter.writeElementString("dzzh" , "");//垫资账号
                reqMsg.append("<dzzh></dzzh>");//垫资账号

                xmlWriter.writeEndDocument();

                String signMsg = signData(reqMsg.toString(), actItem);
                WriteBankLogLn2("签名原始数据:\r\n" + reqMsg.toString());

                String reqData = xmlWriter.toXmlString().replaceAll("<bz1 />", "<bz1>" + signMsg + "</bz1>");

                String[] tmpRetStr = sendToBank(reqData);

                if(tmpRetStr[0].length() == 0) {
                    WriteBankLogStep3(tmpRetStr[1]);

                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);

                    if (tmpBkReader != null) {
                        tmpRetDetail.respCode = "0";
                        tmpRetDetail.respInfo = tmpBkReader.getFirstText("/response/head/fhxx");

                        String tmpRespCode = tmpBkReader.getFirstText("/response/head/fhm");
                        if ("000000".equals(tmpRespCode)) {
                            tmpRetDetail.transState = tmpRespCode;
                            tmpRetDetail.payInfoCode = tmpRespCode;
                        } else {
                            tmpRetDetail.transState = tmpRespCode;
                            tmpRetDetail.payInfoCode = tmpRespCode;
                        }
                    } else {
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = tmpSbMsg.toString();
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpRetStr[1];
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }
    /**
     * 开发接口：
     * 1. 3.3.3.6	交易结果查询[0006]
     */
    @Override
    public RetAtsSingle d_9144_QryRealTimeRec(ReqQrySingle p_req9144) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req9144.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        tmpRetDetail.reqSeqID = p_req9144.askNumber;

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req9144.recAct, "");
            if (actItem != null) {
                CZB02Header bankHeader = new CZB02Header();
                bankHeader.transCode = "0006";
                bankHeader.reqSeqNo = p_req9144.askNumber;

                XmlTextWriter xmlWriter = new XmlTextWriter();
                StringBuilder reqMsg = new StringBuilder();

                writeCommonHeader(xmlWriter, actItem, bankHeader);
                xmlWriter.writeStartElement("body");
                xmlWriter.writeElementString("shlsh" , p_req9144.askNumber);//商户流水号
                reqMsg.append("<shlsh>" + p_req9144.askNumber + "</shlsh>");//商户流水号
                xmlWriter.writeEndDocument();

                String signMsg = signData(reqMsg.toString(), actItem);
                WriteBankLogLn2("签名原始数据:\r\n" + reqMsg.toString());

                String reqData = xmlWriter.toXmlString().replaceAll("<bz1 />", "<bz1>" + signMsg + "</bz1>");

                String[] tmpStrRet = sendToBank(reqData);

                if(tmpStrRet[0].length() == 0) {
                    WriteBankLogStep3(tmpStrRet[1]);

                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

                    if (tmpBkReader != null) {
                        tmpRetDetail.respCode = "0";
                        tmpRetDetail.respInfo = tmpBkReader.getFirstText("/response/head/fhxx");

                        String tmpRespCode = tmpBkReader.getFirstText("/response/head/fhm");
                        if ("000000".equals(tmpRespCode)) {
                            String amount = tmpBkReader.getFirstText("/response/head/hkje");
                            if (StringHelper.hasAnyChar(amount)) {
                                tmpRetDetail.transAmt = StringHelper.amountDivide100(amount);
                            }
                            String tmpTransState = tmpBkReader.getFirstText("/response/body/zt");
                            String tmpErrMsg = tmpBkReader.getFirstText("/response/body/jgxx");

                            tmpRetDetail.transState = tmpRespCode + "+" + tmpTransState;
                            tmpRetDetail.payInfoCode = tmpRespCode;

                            if ("1".equals(tmpTransState)) {
                                tmpRetDetail.respInfo = tmpErrMsg;
                                tmpRetDetail.payInfoCode = tmpErrMsg;
                            }
                        } else {
                            tmpRetDetail.respCode = "-1";
                            if ("000104".equals(tmpRespCode)) {
                                if (canBeNotExist(p_req9144,tmpRetDetail, 45)) {
                                    tmpRetDetail.respCode = "0";
                                    tmpRetDetail.transState = tmpRespCode;
                                    tmpRetDetail.payInfoCode = tmpRespCode;
                                }
                            }
                        }
                    } else {
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = tmpSbMsg.toString();
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpStrRet[1];
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "未找到账号:[" + p_req9144.recAct + "]商户配置信息!";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }
}
